package com.example.orderservice.service;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.pattern.Patterns;
import akka.persistence.query.PersistenceQuery;
import akka.persistence.query.journal.leveldb.javadsl.LeveldbReadJournal;
import akka.persistence.query.journal.leveldb.javadsl.LeveldbReadJournal$;
import akka.stream.ActorMaterializer;
import akka.stream.Materializer;
import akka.stream.javadsl.Sink;
import akka.util.Timeout;
import com.example.orderservice.actor.PersistentOrderActor;
import com.example.orderservice.event.OrderEvent;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CompletableFuture;

/**
 * 事件查询服务
 * 提供事件溯源查询功能
 */
@Slf4j
@Service
public class EventQueryService {
    
    @Autowired
    private ActorSystem actorSystem;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    private final Timeout timeout = Timeout.create(Duration.ofSeconds(10));
    private final Materializer materializer = ActorMaterializer.create(actorSystem);
    
    /**
     * 查询指定订单的所有事件
     */
    public CompletionStage<List<OrderEvent>> getOrderEvents(String orderId) {
        log.info("查询订单事件: {}", orderId);
        
        try {
            // 创建 Actor 来查询事件
            ActorRef orderActor = actorSystem.actorOf(PersistentOrderActor.props(), "order-" + orderId);
            
            // 使用 Akka Persistence Query 查询事件
            LeveldbReadJournal readJournal = PersistenceQuery.get(actorSystem)
                .getReadJournalFor(LeveldbReadJournal.class, LeveldbReadJournal.Identifier());
            
            String persistenceId = "order-" + orderId;
            
            return readJournal
                .eventsByPersistenceId(persistenceId, 0L, Long.MAX_VALUE)
                .map(envelope -> {
                    try {
                        // 将事件转换为 OrderEvent
                        if (envelope.event() instanceof OrderEvent) {
                            return (OrderEvent) envelope.event();
                        }
                        return null;
                    } catch (Exception e) {
                        log.error("解析事件失败: {}", e.getMessage(), e);
                        return null;
                    }
                })
                .filter(event -> event != null)
                .runWith(Sink.seq(), materializer)
                .thenApply(events -> {
                    List<OrderEvent> eventList = new ArrayList<>();
                    events.forEach(eventList::add);
                    log.info("查询到 {} 个事件", eventList.size());
                    return eventList;
                });
                
        } catch (Exception e) {
            log.error("查询订单事件失败: {}", e.getMessage(), e);
            return CompletableFuture.completedFuture(new ArrayList<>());
        }
    }
    
    /**
     * 重建订单状态
     */
    public CompletionStage<PersistentOrderActor.OrderState> rebuildOrderState(String orderId) {
        log.info("重建订单状态: {}", orderId);
        
        try {
            ActorRef orderActor = actorSystem.actorOf(PersistentOrderActor.props(), "order-" + orderId);
            
            PersistentOrderActor.GetOrderStatus getStatusCmd = new PersistentOrderActor.GetOrderStatus(orderId);
            
            return Patterns.ask(orderActor, getStatusCmd, timeout)
                .thenApply(response -> {
                    PersistentOrderActor.OrderStatus result = (PersistentOrderActor.OrderStatus) response;
                    return result.getState();
                });
                
        } catch (Exception e) {
            log.error("重建订单状态失败: {}", e.getMessage(), e);
            return CompletableFuture.completedFuture(new PersistentOrderActor.OrderState());
        }
    }
    
    /**
     * 查询所有订单的摘要信息
     */
    public CompletionStage<List<OrderSummary>> getAllOrderSummaries() {
        log.info("查询所有订单摘要");
        
        try {
            // 这里可以实现更复杂的查询逻辑
            // 例如：查询所有订单的创建事件，构建摘要列表
            return CompletableFuture.completedFuture(new ArrayList<>());
            
        } catch (Exception e) {
            log.error("查询订单摘要失败: {}", e.getMessage(), e);
            return CompletableFuture.completedFuture(new ArrayList<>());
        }
    }
    
    /**
     * 订单摘要类
     */
    public static class OrderSummary {
        private String orderId;
        private String customerId;
        private String status;
        private Double totalAmount;
        private String createdAt;
        
        public OrderSummary() {}
        
        public OrderSummary(String orderId, String customerId, String status, Double totalAmount, String createdAt) {
            this.orderId = orderId;
            this.customerId = customerId;
            this.status = status;
            this.totalAmount = totalAmount;
            this.createdAt = createdAt;
        }
        
        // Getters and Setters
        public String getOrderId() { return orderId; }
        public void setOrderId(String orderId) { this.orderId = orderId; }
        
        public String getCustomerId() { return customerId; }
        public void setCustomerId(String customerId) { this.customerId = customerId; }
        
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
        
        public Double getTotalAmount() { return totalAmount; }
        public void setTotalAmount(Double totalAmount) { this.totalAmount = totalAmount; }
        
        public String getCreatedAt() { return createdAt; }
        public void setCreatedAt(String createdAt) { this.createdAt = createdAt; }
    }
}
